package org.budo.mongo.jdbc.driver.statement.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcPreparedStatement;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcResultSetMetaData;
import org.budo.mongo.jdbc.driver.resultset.MongoCursorResultSet;
import org.budo.mongo.jdbc.driver.statement.AbstractMongoStatement;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;

/**
 * @author lmw
 */
public class MongoAggregateStatement extends AbstractMongoStatement {
    private static final Logger log = Slf4j.getLogger();

    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException{
        BudoMongoJdbcPreparedStatement mongoPreparedStatement = (BudoMongoJdbcPreparedStatement) preparedStatement;
        MongoCollection<Document> mongoCollection = this.getMongoCollection(mongoPreparedStatement);
        Map<String, Object> statementDocument = this.getStatementDocumentWithParameterValues(mongoPreparedStatement.getParameterMap());

        log.debug("execute(), statementDocument={}, sql={}, parameterMap={}", statementDocument, this.sql(), mongoPreparedStatement.getParameterMap());

        List<Document> aggregatePipeline = (List<Document>) statementDocument.get(AGGREGATE_PIPELINE);

        AggregateIterable<Document> aggregateIterable = mongoCollection.aggregate(aggregatePipeline);

        MongoCursorResultSet mongoJdbcResultSet = new MongoCursorResultSet();
        BudoMongoJdbcResultSetMetaData resultSetMetaData = this.getResultSetMetaData();
        mongoJdbcResultSet.setMetaData(resultSetMetaData);
        mongoJdbcResultSet.setMongoCursor(aggregateIterable.iterator());

        mongoPreparedStatement.resultSet(mongoJdbcResultSet);
    }
}